using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [Header("移动设置")]
    public float moveSpeed = 8f;
    public float smoothTime = 0.1f;
    
    [Header("输入设置")]
    public KeyCode leftKey = KeyCode.A;
    public KeyCode rightKey = KeyCode.D;
    public KeyCode leftArrowKey = KeyCode.LeftArrow;
    public KeyCode rightArrowKey = KeyCode.RightArrow;
    
    [Header("调试信息")]
    public bool showDebugInfo = true;
    
    [Header("生命值设置")]
    public float maxHealth = 100f;
    public float currentHealth = 100f;
    
    private Rigidbody2D rb;
    private Vector2 movement;
    private Vector2 velocity;
    private float horizontalInput;
    
    // 触摸输入相关
    private bool isTouchControlEnabled = true;
    private Vector2 lastTouchPosition;
    
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        
        if (rb == null)
        {
            rb = gameObject.AddComponent<Rigidbody2D>();
        }
        
        // 设置刚体属性
        rb.gravityScale = 0f; // 2D弹幕游戏不需要重力
        rb.freezeRotation = true; // 防止旋转
        
        // 确保玩家在屏幕底部
        Vector3 startPosition = transform.position;
        startPosition.y = -4f; // 屏幕底部位置
        transform.position = startPosition;
        
        Debug.Log("玩家控制器已初始化");
        
        // 初始化生命值
        currentHealth = maxHealth;
    }
    
    void Update()
    {
        HandleInput();
        
        if (showDebugInfo)
        {
            Debug.Log($"玩家位置: {transform.position}, 输入: {horizontalInput}");
        }
    }
    
    void FixedUpdate()
    {
        MovePlayer();
    }
    
    void HandleInput()
    {
        // 键盘输入
        horizontalInput = 0f;
        
        if (Input.GetKey(leftKey) || Input.GetKey(leftArrowKey))
        {
            horizontalInput -= 1f;
        }
        
        if (Input.GetKey(rightKey) || Input.GetKey(rightArrowKey))
        {
            horizontalInput += 1f;
        }
        
        // 触摸输入（移动端支持）
        if (isTouchControlEnabled && Input.touchCount > 0)
        {
            HandleTouchInput();
        }
        
        // 鼠标输入（用于测试）
        if (Input.GetMouseButton(0))
        {
            HandleMouseInput();
        }
    }
    
    void HandleTouchInput()
    {
        Touch touch = Input.GetTouch(0);
        Vector2 touchWorldPos = Camera.main.ScreenToWorldPoint(touch.position);
        
        if (touch.phase == TouchPhase.Began)
        {
            lastTouchPosition = touchWorldPos;
        }
        else if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
        {
            float deltaX = touchWorldPos.x - lastTouchPosition.x;
            
            if (Mathf.Abs(deltaX) > 0.1f)
            {
                horizontalInput = Mathf.Sign(deltaX);
                lastTouchPosition = touchWorldPos;
            }
        }
    }
    
    void HandleMouseInput()
    {
        Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float deltaX = mouseWorldPos.x - transform.position.x;
        
        if (Mathf.Abs(deltaX) > 0.5f)
        {
            horizontalInput = Mathf.Sign(deltaX);
        }
    }
    
    void MovePlayer()
    {
        // 计算目标速度
        Vector2 targetVelocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
        
        // 平滑移动
        rb.velocity = Vector2.SmoothDamp(rb.velocity, targetVelocity, ref velocity, smoothTime);
        
        // 边界限制
        if (BoundaryManager.Instance != null)
        {
            Vector3 clampedPosition = BoundaryManager.Instance.ClampToBoundary(transform.position);
            transform.position = clampedPosition;
        }
    }
    
    void OnDrawGizmos()
    {
        if (showDebugInfo)
        {
            // 绘制移动方向
            Gizmos.color = Color.green;
            Gizmos.DrawLine(transform.position, transform.position + Vector3.right * horizontalInput * 2f);
            
            // 绘制玩家范围
            Gizmos.color = Color.blue;
            Gizmos.DrawWireSphere(transform.position, 0.5f);
        }
    }
    
    // 公共方法：获取玩家位置（供其他脚本使用）
    public Vector3 GetPlayerPosition()
    {
        return transform.position;
    }
    
    // 公共方法：获取移动方向
    public float GetMovementDirection()
    {
        return horizontalInput;
    }
    
    // 生命值相关方法
    public float GetCurrentHealth()
    {
        return currentHealth;
    }
    
    public float GetMaxHealth()
    {
        return maxHealth;
    }
    
    public void TakeDamage(float damage)
    {
        currentHealth = Mathf.Max(0f, currentHealth - damage);
        
        if (currentHealth <= 0f)
        {
            // 玩家死亡
            if (GameManager.Instance != null)
            {
                GameManager.Instance.HandlePlayerDied();
            }
        }
        
        if (showDebugInfo)
        {
            Debug.Log($"玩家受到伤害: {damage}, 当前生命值: {currentHealth}/{maxHealth}");
        }
    }
    
    public void Heal(float healAmount)
    {
        currentHealth = Mathf.Min(maxHealth, currentHealth + healAmount);
        
        if (showDebugInfo)
        {
            Debug.Log($"玩家恢复生命值: {healAmount}, 当前生命值: {currentHealth}/{maxHealth}");
        }
    }
}